<template>
  <basic-container>
    <div v-loading="saving">
      <basic-page-header @back="goBack"></basic-page-header>
      <!-- <div>
        <el-button @click="goBack" icon="el-icon-back" type="text" size="small">返回</el-button>
      </div> -->
      <!-- <el-page-header @back="goBack" :content="headerTitle"></el-page-header> -->
      <el-divider></el-divider>

      <el-form size="small" ref="form" :rules="rules" :model="form" label-width="100px">
        <el-collapse v-model="activeNames" style="border-top: none;">
          <el-collapse-item title="基本信息" name="1">
            <el-row class="w-95p pad-lr-15 mar-t-15">
              <el-col>
                <el-form-item label="任务名称" prop="name">
                  <el-input class="w-250" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                  <el-input type="textarea" :rows="3" v-model="form.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="数据来源与去向" name="2">
            <el-row class="w-95p mar-t-15">
              <el-col :span="12"><el-divider direction="vertical"></el-divider> 数据来源</el-col>
              <el-col :span="12"><el-divider direction="vertical"></el-divider> 数据去向</el-col>
            </el-row>
            <el-row type="flex" :gutter="15" class="w-95p pad-lr-15 mar-t-10">
              <el-col class="bor pad-t-15 mar-r-15" :span="12">
                <div>
                  <el-form-item label="数据源">
                    <el-select style="width: calc(50% - 10px)" @change="datasourceTypeChange('source');dsType = form.processDefinitionJson.tasks[0].params.dsType" v-model="form.processDefinitionJson.tasks[0].params.dsType" placeholder="请选择数据源类型">
                      <el-option v-for="item of datasourceTypeList" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    <el-select class="mar-l-20" style="width: calc(50% - 10px)" @change="datasourceChange('source')" v-model="form.processDefinitionJson.tasks[0].params.dataSource" placeholder="请选择数据源">
                      <el-option v-for="item of datasources._source" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <template v-if="dsType !== 'FTP' && dsType !== 'API' && dsType !== 'KAFKA'">
                    <el-form-item label="表" prop="processDefinitionJson.tasks.0.params.sourceTable">
                      <el-select class="dis-b" @change="tableChange('source')"  v-model="form.processDefinitionJson.tasks[0].params.sourceTable" placeholder="请选择表">
                        <el-option v-for="item of tables._source" :label="item" :value="item"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="SQL">
                      <el-input type="textarea" :rows="3" v-model="form.processDefinitionJson.tasks[0].params.where"></el-input>
                    </el-form-item>
                  </template>
                  <template v-if="dsType === 'FTP'">
                    <el-form-item label="数据源路径">
                      <el-cascader
                        class="dis-b"
                        @change="recursionDirChange('source')"
                        v-model="sourcePath"
                        :options="recursionDirs['source']"
                        :props="{ checkStrictly: true }"></el-cascader>
                      <!-- <el-input v-model="form.processDefinitionJson.tasks[0].params.sourcePath"></el-input> -->
                    </el-form-item>
                    <!-- <el-form-item label="文件筛选">
                      <el-radio-group v-model="ftp.ds.fileSelection">
                        <el-radio :label="1">全部</el-radio>
                        <el-radio :label="2">部分</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="文件切分">
                      <el-radio-group v-model="ftp.ds.fileSlice" @change="() => {ftp.ds.fileSliceType = ''; ftp.dt.fileSliceType = '';}">
                        <el-radio :label="1">不切分</el-radio>
                        <el-radio :label="2">切分</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="切分格式" v-if="ftp.ds.fileSlice === 2">
                      <el-select v-model="ftp.ds.fileSliceType" placeholder="请选择">
                        <el-option
                          v-for="item in fileSliceTypes"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="特殊字符替换">
                      <el-switch
                        v-model="ftp.ds.replace.open">
                      </el-switch>
                      <template v-if="ftp.ds.replace.open">
                        字符<el-input placeholder="\n,\r,\01" class="dis-ib w-80" width="100" v-model="ftp.ds.replace.source"></el-input>
                        替换为<el-input class="dis-ib w-80" width="100" v-model="ftp.ds.replace.target"></el-input>
                      </template>
                    </el-form-item>
                    <el-form-item label="高级配置">
                      <template>
                        <el-table :data="ftp.ds.propsList">
                          <el-table-column
                            prop="name"
                            label="属性">
                            <template slot-scope="{row}">
                              <el-input size="small" v-model="row.name"></el-input>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="value"
                            label="值">
                            <template slot-scope="{row}">
                              <el-input size="small" v-model="row.value"></el-input>
                            </template>
                          </el-table-column>
                          <el-table-column width="50">
                            <template slot-scope="scope">
                              <el-button type="text" size="small" icon="el-icon-circle-close" @click="() => {ftp.ds.propsList.splice(scope.$index , 1)}"></el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                        <el-button type="text" icon="el-icon-circle-plus-outline" @click="ftp.ds.propsList.push({name: '' , value: ''})">添加</el-button>
                      </template>
                    </el-form-item> -->
                  </template>
                  <template v-if="dsType === 'API'">
                    <el-form-item label="接口地址">
                      <el-input :value="api.source.url"></el-input>
                    </el-form-item>
                    <el-form-item label="入参">
                      <template>
                        <el-table :data="api.source.reqParams">
                          <el-table-column
                            prop="name"
                            label="属性">
                          </el-table-column>
                          <el-table-column
                            prop="value"
                            label="值">
                          </el-table-column>
                        </el-table>
                      </template>
                    </el-form-item>
                  </template>
                </div>
              </el-col>
              <el-col class="bor pad-t-15" :span="12">
                <div>
                  <el-form-item label="目标库">
                    <el-select style="width: calc(50% - 10px)" @change="datasourceTypeChange('target');dtType = form.processDefinitionJson.tasks[0].params.dtType" v-model="form.processDefinitionJson.tasks[0].params.dtType" placeholder="请选择数据源类型">
                      <el-option v-for="item of datasourceTypeList" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    <el-select class="mar-l-20" style="width: calc(50% - 10px)" @change="datasourceChange('target')" v-model="form.processDefinitionJson.tasks[0].params.dataTarget" placeholder="请选择数据源">
                      <el-option v-for="item of datasources._target" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <template v-if="dtType !== 'FTP' && dtType !== 'API' && dtType !== 'KAFKA'"  >
                    <el-form-item label="表" prop="processDefinitionJson.tasks.0.params.targetTable">
                      <el-select @change="tableChange('target')" class="dis-b" v-model="form.processDefinitionJson.tasks[0].params.targetTable" placeholder="请选择表">
                        <el-option v-for="item of tables._target" :label="item" :value="item"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="前置SQL">
                      <i class="el-icon-circle-plus-outline text-blue cur-p fts-18" @click="() => this.form.processDefinitionJson.tasks[0].params.preStatements.push('')"></i>
                      <div class="mar-b-5" v-for="(item , index) of form.processDefinitionJson.tasks[0].params.preStatements">
                        <el-input class="dis-ib" style="width: calc(100% - 40px)" v-model="form.processDefinitionJson.tasks[0].params.preStatements[index]"></el-input>
                        <div class="dis-ib w-35 text-center">
                          <i class="el-icon-remove-outline text-danger fts-18 cur-p" @click="() => form.processDefinitionJson.tasks[0].params.preStatements.splice(index , 1)"></i>
                        </div>
                      </div>
                    </el-form-item>
                    <el-form-item label="后置SQL">
                      <i class="el-icon-circle-plus-outline text-blue cur-p fts-18" @click="() => this.form.processDefinitionJson.tasks[0].params.postStatements.push('')"></i>
                      <div class="mar-b-5" v-for="(item , index) of form.processDefinitionJson.tasks[0].params.postStatements">
                        <el-input class="dis-ib" style="width: calc(100% - 40px)" v-model="form.processDefinitionJson.tasks[0].params.postStatements[index]"></el-input>
                        <div class="dis-ib w-35 text-center">
                          <i class="el-icon-remove-outline text-danger fts-18 cur-p" @click="() => form.processDefinitionJson.tasks[0].params.postStatements.splice(index , 1)"></i>
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                  <template v-if="dtType === 'FTP'" >
                    <el-form-item label="数据源路径">
                      <el-cascader
                        @change="recursionDirChange('target')"
                        class="dis-b"
                        v-model="targetPath"
                        :options="recursionDirs['target']"
                        :props="{ checkStrictly: true }"></el-cascader>
                      <!-- <el-input v-model="form.processDefinitionJson.tasks[0].params.targetPath"></el-input> -->
                    </el-form-item>
                    <!-- <el-form-item label="切分格式" v-if="ftp.ds.fileSlice === 2">
                      <el-select v-model="ftp.dt.fileSliceType" placeholder="请选择">
                        <el-option
                          v-for="item in fileSliceTypes"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="高级配置">
                      <template>
                        <el-table :data="ftp.dt.propsList">
                          <el-table-column
                            prop="name"
                            label="属性">
                            <template slot-scope="{row}">
                              <el-input size="small" v-model="row.name"></el-input>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="value"
                            label="值">
                            <template slot-scope="{row}">
                              <el-input size="small" v-model="row.value"></el-input>
                            </template>
                          </el-table-column>
                          <el-table-column width="50">
                            <template slot-scope="scope">
                              <el-button type="text" size="small" icon="el-icon-circle-close" @click="() => {ftp.dt.propsList.splice(scope.$index , 1)}"></el-button>
                            </template>
                          </el-table-column>
                        </el-table>
                        <el-button type="text" icon="el-icon-circle-plus-outline" @click="ftp.dt.propsList.push({name: '' , value: ''})">添加</el-button>
                      </template>
                    </el-form-item> -->
                  </template>
                  <template v-if="dtType === 'API'">
                    <el-form-item label="接口地址">
                      <el-input :value="api.target.url"></el-input>
                    </el-form-item>
                    <el-form-item label="入参">
                      <template>
                        <el-table :data="api.target.reqParams">
                          <el-table-column
                            prop="name"
                            label="属性">
                          </el-table-column>
                          <el-table-column
                            prop="value"
                            label="值">
                          </el-table-column>
                        </el-table>
                      </template>
                    </el-form-item>
                  </template>
                </div>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="字段映射" name="3">
            <el-row class="mar-t-15" :gutter="15">
              <el-col class="lh-40 bg-gray-4 pad-lr-15 mar-b-0" :span="8">源字段</el-col>
              <el-col class="lh-40 bg-gray-4 pad-lr-15 mar-b-0" :span="16">目标字段</el-col>
            </el-row>
            <div style="max-height: 250px;" class="ov-h ov-a-y">
              <el-row v-for="item of columns._target" class="bor-b pad-t-8" :gutter="15">
                <el-col class="lh-32 pad-lr-15" :span="8">
                  <el-select @change="columnCahge()" size="small" class="dis-b" v-model="columns.values[item.value]" placeholder="请选择表">
                    <el-option v-for="item of columns._default.concat(columns._source)" :label="item.name" :value="item.value"></el-option>
                  </el-select>
                </el-col>
                <el-col class="lh-32 pad-lr-15" :span="16">{{item.name}}</el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>

        <basic-form-button @submit="submitForm('form')" @cancel="goBack"></basic-form-button>

      </el-form>
      
    </div>
  </basic-container>
</template>
<script>
import { mapActions } from 'vuex'
import datasourceTypeList from '@/config/datasourceTypeList';
import md5 from '@/util/md5';

export default {
  data(){
    return {
      headerTitle: '',
      saving: false,
      datasourceTypeList: datasourceTypeList,
      sourcePath: [],
      targetPath: [],
      recursionDirs: {
        source: [],
        target: []
      },
      datasources: {
        _source: [],
        _target: []
      },
      api: {
        source: {
          url: '',
          reqParams: []
        },
        target: {
          url: '',
          reqParams: []
        }
      },
      columns: {
        _source: [],
        _target: [],
        _default: [
          {name: '不导入' , value: ''}
        ],
        values: {}
      },
      tables: {
        _source: [],
        _target: []
      },
      activeNames: ['1' , '2' , '3'],
      oldName: '',
      fileSliceTypes: [
        {name: 'text' , value: 'text'},
        {name: 'json' , value: 'json'},
        {name: 'csv' , value: 'csv'},
        {name: 'excel' , value: 'excel'}
      ],
      ftp: {
        ds: {
          datasourceUrl: '',
          fileSelection: 1,
          fileSlice: 2,
          fileSliceType: '',
          replace: {
            open: false,
            source: '',
            target: ''
          },
          propsList: []
        },
        dt: {
          datasourceUrl: '',
          fileSliceType: '',
          propsList: []
        }
      },
      form: {
        globalParams: [],
        processDefinitionJson: {
          tasks: [{
            name: '',
            type: 'DATAX',
            id: 'tasks-' + Math.ceil(Math.random() * 100000),
            description: '',
            params: {
              dsType: '',
              dtType: '',
              dataSource: null,
              dataTarget: null,
              sourceTable: '',
              targetTable: '',
              where: '',
              preStatements: [],
              postStatements: [],
              targetCloumns: [],
              sourceCloumns: [],
              // 待确认
              jobSpeedByte: 0,
              jobSpeedRecord: 1000,
              customConfig: 0,
              sourcePath: '',
              targetPath: ''
            },
            // 待确认
            timeout: {
              "strategy": "",
              "interval": null,
              "enable": false
            },
            runFlag: 'NORMAL',
            conditionResult: {
              successNode: [],
              failedNode: []
            },
            dependence: {},
            maxRetryTimes: '0',
            retryInterval: '1',
            taskInstancePriority: 'MEDIUM',
            workerGroup: 'default',
            preTasks: []
          }],
          tenantId: 1,
          timeout: 0
        },
        name: '',
        type: '2',
        description: '',
        connects: [],
        locations: {}
      },
      rules: {
        name: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        'processDefinitionJson.tasks.0.params.targetTable': [
          { required: true, message: '目标库表不能为空', trigger: 'change' }
        ],
        'processDefinitionJson.tasks.0.params.sourceTable': [
          { required: true, message: '数据源表不能为空', trigger: 'change' }
        ]
      },
      baseDataHash: '',
      dsType: '',
      dtType: ''
    }
  },
  created(){
    this.headerTitle = this.$router.currentRoute.name;
    this.$breadcrumb.breadcrumbs.length < 5 && this.$breadcrumb.add({
      name: this.headerTitle,
      path: this.$router.currentRoute.path
    });
  },
  mounted(){
    if(this.$router.currentRoute.params.id !== undefined){
      this.saving = true;
      this.getProcessDetails(this.$router.currentRoute.params.id).then(
        res => {
          this.saving = false;
          this.form = res;
          this.form.processDefinitionJson = JSON.parse(res['processDefinitionJson']);
          this.form.locations = JSON.parse(res['locations']);
          this.form.connects = JSON.parse(res['connects']);
          this.dsType = this.form.processDefinitionJson.tasks[0].params.dsType;
          this.dtType = this.form.processDefinitionJson.tasks[0].params.dtType;
          this.sourcePath = this.form.processDefinitionJson.tasks[0].params.sourcePath.split('/').slice(1);
          this.targetPath = this.form.processDefinitionJson.tasks[0].params.targetPath.split('/').slice(1 , -1);
          this.oldName = this.form.name;
          ['source' , 'target'].forEach(
            type => {
              this.datasourceTypeChange(type , true);
              this.datasourceChange(type , true);

              // this.tableChange(type , (type) => {
              //   if(type === 'target' && this.dtType !== 'KAFKA'){
              //     this.setColumnsValue();
              //   }
              // })
            }
          )
          this.setColumnsValue();
          if(this.dsType !== 'KAFKA'){
            this.tableChange('source' , true);
          }
          if(this.dtType !== 'KAFKA'){
            this.tableChange('target' , true);
          }
          this.baseDataHash = md5.str_md5(JSON.stringify(this.form));
        }
      ).catch(() => {
        this.saving = false;
      })
    }else{
      this.baseDataHash = md5.str_md5(JSON.stringify(this.form));
    }
  },
  destroyed(){
    // this.$breadcrumb.pop();
  },
  methods: {
    ...mapActions('datasource', ['getDatasourcesList' , 'getTablesByDatasourceId' , 'getColumns' , 'recursionDir' , 'recursionDirFile']),
    ...mapActions('dag' , ['saveTask' , 'updateTask' , 'verifDAGName' , 'getProcessDetails']), 
    goBack(saved){
      if(!saved && this.baseDataHash !== md5.str_md5(JSON.stringify(this.form))){
        this.$confirm(`您所编辑的数据都会丢失，确定要返回？` , `提示` , {
          type: 'warning'
        }).then(() => {
          this.$breadcrumb.pop();
          this.$router.back();
        })
      }else{
        this.$breadcrumb.pop();
        this.$router.back();
      }
    },
    createTestData(obj , name , value , type){
      let len = Math.ceil(Math.random() * 5);
      obj[value] = [];
      for(let i = 0; i < len; i++){
        obj[value].push({
          name: `${value}-${name}-${i + 1}`,
          id: Math.ceil(Math.random() * 100000) + 100000
        })
      }
      obj[type] = obj[value];
    },
    datasourceTypeChange(type , noClear){
      if(!noClear){
        this.form.processDefinitionJson.tasks[0].params[type === 'source' ? 'dataSource' : 'dataTarget'] = null;
        this.form.processDefinitionJson.tasks[0].params[type === 'source' ? 'sourceTable' : 'targetTable'] = '';
      }
      let name = type === 'source' ? 'dsType' : 'dtType';
      let dType = this.form.processDefinitionJson.tasks[0].params[name];
      if(this[`datasourceTypeChange_${dType}`]){
        this[`datasourceTypeChange_${dType}`](type , noClear);
      }else{
        this.defaultDatasourceTypeChange(type , noClear);
      }
    },
    // default
    defaultDatasourceTypeChange(type , noClear){
  
      let name = type === 'source' ? 'dsType' : 'dtType';
      if(!this.datasources[this.form.processDefinitionJson.tasks[0].params[name]]){
        this.getDatasourcesList({
          type: this.form.processDefinitionJson.tasks[0].params[name]
        }).then(
          res => {
            this.datasources[`_${type}`] = res.data || [];
          }
        )
      }
    },
    datasourceChange(type , noClear){
      if(!noClear){
        this.form.processDefinitionJson.tasks[0].params[type === 'source' ? 'sourceTable' : 'targetTable'] = '';
      }
      let name = type === 'source' ? 'dsType' : 'dtType';
      let dType = this.form.processDefinitionJson.tasks[0].params[name];
      if(dType !== 'KAFKA'){
        if(this[`datasourceChange_${dType}`]){
          this[`datasourceChange_${dType}`](type , noClear);
        }else{
          this.defaultDatasourceChange(type , noClear);
        }
      }else{
        this.useDatasourceChangeKAFKA(noClear);
      }
    },
    datasourceChangeKAFKA(type , noClear){
      let targetType = type === 'source' ? 'target' : 'source';
      let values = {};
      let data = [];
      console.log(type , this.columns);
      this.columns['_' + targetType].forEach(
        v => {
          data.push({
            name: v.name,
            value: v.value
          })
          if(!noClear){
            if(type === 'target'){
              values[v.name] = '';
            }
          }
        }
      )
      this.columns['_' + type] = data;
      if(!noClear){
        if(type === 'target'){
          this.columns.values = values;
        }
      }
    },
    useDatasourceChangeKAFKA(noClear){
      if(this.form.processDefinitionJson.tasks[0].params['dsType'] === 'KAFKA'){
        this.datasourceChangeKAFKA('source' , noClear);
      }else if(this.form.processDefinitionJson.tasks[0].params['dtType'] === 'KAFKA'){
        this.datasourceChangeKAFKA('target' , noClear);
      }
    },
    datasourceChange_API(type , noClear){
      let datasourceName = type === 'source' ? 'dataSource' : 'dataTarget';
      let name = type === 'source' ? 'dsType' : 'dtType';
      let id = this.form.processDefinitionJson.tasks[0].params[datasourceName];
      let handle = (datalist) => {
        datalist.forEach(
          item => {
            if(item.id === id){
              let connectionParams = JSON.parse(item.connectionParams);
              let respParams = JSON.parse(connectionParams.respParams) || [];
              let data = [];
              this.api[type].url = connectionParams.apiUrl;
              this.api[type].reqParams = JSON.parse(connectionParams.reqParams) || [];
              let values = {};
              respParams.forEach(
                v => {
                  data.push({
                    name: v.name,
                    value: v.name
                  })
                  if(type === 'target'){
                    values[v.name] = '';
                  }
                }
              )
              this.columns['_' + type] = data;
              if(type === 'target'){
                this.columns.values = values;
              }
            }
          }
        )
        this.useDatasourceChangeKAFKA(noClear);
      }
      if(this.datasources[`_${type}`].length){
        handle(this.datasources[`_${type}`])
      }else{
        this.getDatasourcesList({
          type: this.form.processDefinitionJson.tasks[0].params[name]
        }).then(
          res => {
            handle(res.data || []);
          }
        )
      }
    },
    defaultDatasourceChange(type , noClear){
      let datasourceName = type === 'source' ? 'dataSource' : 'dataTarget';
      if((type === 'source' && this.dsType !== 'FTP') || (type === 'target' && this.dtType !== 'FTP')){
        if(!this.tables[this.form.processDefinitionJson.tasks[0].params[datasourceName]]){
          this.getTablesByDatasourceId(this.form.processDefinitionJson.tasks[0].params[datasourceName]).then(
            res => {
              if(res.data.data){
                this.tables[`_${type}`] = res.data.data || [];
              }
            }
          )
        }
      }
      if((type === 'source' && this.dsType === 'FTP') || (type === 'target' && this.dtType === 'FTP')){
        (type === 'target' ? this.recursionDir : this.recursionDirFile)({
          datasourceId: this.form.processDefinitionJson.tasks[0].params[datasourceName],
          directory: '/'
        }).then(
          res => {
            this.recursionDirs[type] = this.resetRecursionDir(res.data.data.children , type);
          }
        )
      }
    },
    recursionDirChange(type){
      let name = type + 'Path';
      this.form.processDefinitionJson.tasks[0].params[name] = '/' + this[name].join('/') + (type === 'target' ? '/' : '');
    },
    resetRecursionDir(data , type){
      data.forEach(
        item => {
          item.label = item.name;
          if(!item.isAll){
            item.value = item.name;
          }
          if(item.children && item.children.length){
            if(type === 'source'){
              item.children.unshift({
                name: '全部',
                value: '*',
                isAll: true
              })
            }
            item.children = this.resetRecursionDir(item.children , type);
          }else{
            delete item.children;
          }
        }
      )
      return data;
    },
    tableChange(type , noClear , callback){

      this.columns['_' + type] = [];
      let values = {};
      let datasourceName = type === 'source' ? 'dataSource' : 'dataTarget';
      let tableName = type === 'source' ? 'sourceTable' : 'targetTable';
      if(this.form.processDefinitionJson.tasks[0].params[datasourceName] && this.form.processDefinitionJson.tasks[0].params[tableName]){
        this.getColumns({
          datasourceId: this.form.processDefinitionJson.tasks[0].params[datasourceName],
          tableName: this.form.processDefinitionJson.tasks[0].params[tableName]
        }).then(
          res => {
            if(res.data.data){
              let data = [];
              res.data.data.forEach(
                v => {
                  data.push({
                    name: v,
                    value: v
                  })
                  if(!noClear){
                    if(type === 'target'){
                      values[v.name] = '';
                    }
                  }
                }
              )
              this.columns['_' + type] = data;
              if(!noClear){
                if(type === 'target'){
                  this.columns.values = values;
                }
              }
            }
            this.useDatasourceChangeKAFKA(noClear);
            callback && callback(type);
          }
        )
      }
    },
    columnCahge(){
      let targetCloumns = [];
      let sourceCloumns = [];
      Object.keys(this.columns.values).forEach(
        key => {
          if(this.columns.values[key]){
            targetCloumns.push(key);
            sourceCloumns.push(this.columns.values[key])
          }
        }
      )
      this.form.processDefinitionJson.tasks[0].params.targetCloumns = targetCloumns;
      this.form.processDefinitionJson.tasks[0].params.sourceCloumns = sourceCloumns;
    },
    setColumnsValue(){
      if(this.form.processDefinitionJson.tasks[0].params.targetCloumns){
        let values = {};
        this.form.processDefinitionJson.tasks[0].params.targetCloumns.forEach(
          (item , index) => {
            values[item] = this.form.processDefinitionJson.tasks[0].params.sourceCloumns[index];
          }
        )
        this.columns.values = values;
      }
    },
    _saveTask(){
      (this.form.id ? this.updateTask(this.form) : this.saveTask(this.form)).then(
        res => {
          this.saving = false;
          if(res && res.code === 0){
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.goBack(true)
          }else{
            this.$message({
              type: 'error',
              message: res['msg'] || '保存失败'
            })
          }
        }
      ).catch((e) => {
        this.saving = false;
      })
    },
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.processDefinitionJson.tasks[0].name = this.form.name;
          this.form.processDefinitionJson.tasks[0].description = this.form.description;
          this.saving = true;
          if(this.oldName !== this.form.name){
            this.verifDAGName(this.form.name).then(
              res => {
                this._saveTask();
              }
            ).catch(() => {
              this.saving = false;
            });
          }else{
            this._saveTask();
          }
        } else {
          this.$message({
            type: 'error',
            message: '请完整填写表单'
          })
          return false;
        }
      });
    }
  }
}
</script>